package poi

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	rentalpb "serve/rental/api/gen/v1"
)

var apiURl = "https://apis.map.qq.com/ws/geocoder/v1?location=%v,%v&get_poi=0&key=OA4BZ-FX43U-E5VV2-45M6S-C4HD3-NIFFI&output=json"

type Manager struct {
}
type FormattedAddresses struct {
	Recommend string `json:"recommend,omitempty"`
	Rough     string `json:"rough,omitempty"`
}

type result struct {
	Location           interface{}        `json:"location,omitempty"`
	Address            string             `json:"address,omitempty"`
	FormattedAddresses FormattedAddresses `json:"formatted_addresses"`
}

type poiContent struct {
	Status    int    `json:"status,omitempty"`
	Message   string `json:"message,omitempty"`
	RequestId string `json:"request_id,omitempty"`
	Result    result `json:"result"`
}

func (m Manager) Resolve(ctx context.Context, location *rentalpb.Location) (string, error) {
	url := fmt.Sprintf(apiURl, location.Latitude, location.Longitude)
	get, err := http.Get(url)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(get.Body)
	if err != nil {
		return "", err
	}

	var poi poiContent
	err = json.Unmarshal(body, &poi)
	if err != nil {
		return "", err
	}

	if poi.Status == 0 && poi.Message == "query ok" {
		return poi.Result.Address + poi.Result.FormattedAddresses.Rough, nil
	}

	return "", fmt.Errorf("未获取到位置信息")
}
